import * as qiniu from 'qiniu-js'

interface UploadResult {
  key: string
  hash: string
  url?: string
}

const QINIU_DOMAIN = 'https://image.lutongjiakao.com'

type ProgressCallback = (percent: number) => void

export const uploadFileToQiniu = async (
  file: File,
  token: string,
  onProgress: ProgressCallback
): Promise<UploadResult> => {
  if (!file) {
    throw new Error('未选择文件！')
  }
  try {
    const uniqueKey = `video/${new Date().getTime()}_${file.name}`

    const config = {
      useCdnDomain: true,
      region: qiniu.region.z2
    }

    const putExtra = {
      fname: file.name,
      params: {},
      mimeType: 'video/mp4'
    }

    const observable = qiniu.upload(file, uniqueKey, token, putExtra, config)

    return new Promise((resolve, reject) => {
      observable.subscribe({
        next(res) {
          const percent = res.total.percent
          onProgress(percent)
        },
        error(err) {
          reject(err)
        },
        complete(res) {
          resolve({
            key: res.key,
            hash: res.hash,
            url: `${QINIU_DOMAIN}/${uniqueKey}`
          })
        }
      })
    })
  } catch (error) {
    console.error('错误:', error)
    throw error
  }
}
